var name = window.localStorage.getItem('name')
$('[name="username"]').val(name)
$('form').on('submit', function () {

    var oldPassword = $('[name="oldPassword"]').val()
    var newPassword = $('[name="newPassword"]').val()
    var rNewPassword = $('[name="rNewPassword"]').val()

    //密码校验
    var reg2 = /\w{6,12}/;
    if (!reg2.test(oldPassword)) {
        layer.msg('旧密码密码不规范', {
            icon: 2,
            time: 1000
        })
        return false
    }
    if (!reg2.test(newPassword)) {
        layer.msg('新密码不规范', {
            icon: 2,
            time: 1000
        })
        return false
    }
    if (!reg2.test(rNewPassword)) {
        layer.msg('再次输入的新密码不规范', {
            icon: 2,
            time: 1000
        })
        return false
    }
    //两次新密码不一致
    if (newPassword !== rNewPassword) {
        layer.msg('两次密码输入不一致', {
            icon: 2,
            time: 1000
        })
        return false
    }
    var xhr = new XMLHttpRequest;
    xhr.open('post', '/api/changepwd');
    xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
    xhr.send(`username=${name}&oldPassword=${oldPassword}&newPassword=${newPassword}&rNewPassword=${rNewPassword}`)
    console.log(name);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
                var res = xhr.responseText;
                res = JSON.parse(res);
                console.log(res);
                if (res.code === 1) {
                    layer.msg(res.msg, {
                        icon: 1,
                        time: 1000
                    }, () => {
                        window.localStorage.removeItem('name')
                        window.localStorage.removeItem('userInfo')
                        location.href = '../login.html'
                    })
                } else {
                    layer.msg(res.msg, {
                        icon: 1,
                        time: 1000
                    }, () => {
                        $('[name="oldPassword"]').val('')
                        $('[name="newPassword"]').val('')
                        $('[name="rNewPassword"]').val('')
                    })
                    return false
                }
            }
        }
    }
    //阻止默认行为
    return false
})